/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.util.WebUtils;

import com.pmc.dwa.common.utils.ConfigParameter;
import com.pmc.dwa.common.utils.Escape;
import com.pmc.dwa.common.utils.Httptear;
import com.pmc.dwa.common.utils.JsonUtils;
import com.pmc.dwa.common.utils.Util;
import com.pmc.dwa.security.model.TRole;
import com.pmc.dwa.security.model.TSect;
import com.pmc.dwa.security.service.ISectionResourceService;
import com.pmc.dwa.security.service.IUserService;
import com.pmc.dwa.security.utils.PmcAttributes;
import com.pmc.dwa.security.utils.SpringSecurityUtils;

/**
 * @description 登录成功进行处理
 * @author aokunsang
 * @date 2013-1-6
 */
public class LoginAuthenticationSuccesssHandler implements
		AuthenticationSuccessHandler {

	private String defaultUrl;   //登录成功后跳转的地址
	private String modesymbol;   //登录类型标示符
	private ISectionResourceService srService;
	private IUserService userService;
	
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication auth) throws IOException,
			ServletException {
		String username = SpringSecurityUtils.getCurrentUser(auth).getUsername();  //用户名
		String groupid = ConfigParameter.getParamVal("sysconf.properties", "groupid"); //获取系统ID 
		String login_mode = request.getParameter(modesymbol);   //获取登录模式
		//记录用户登录信息
		userService.editUserState(username, Util.getIpAddr(request));
		
		//根据用户权限构造JSON格式系统二级菜单
		List<TRole> roles = userService.findUserRolesByUsername(username);
		
		StringBuffer strRoleIdlist = new StringBuffer();
		for(Iterator<TRole> iter = roles.iterator();iter.hasNext();){
			TRole role = iter.next();
			strRoleIdlist.append("'" + role.getId() + "',");
		}
		if(strRoleIdlist.length()!=0 && strRoleIdlist.lastIndexOf(",")!=-1){
			strRoleIdlist.delete(strRoleIdlist.lastIndexOf(","),strRoleIdlist.length());
		}else if(StringUtils.isNotEmpty(login_mode) && PmcAttributes.PMC_LOGIN_MODE.equalsIgnoreCase(login_mode)){  //登录模式为Ajax
			Httptear.ResponseResultByUTF8("{\"success\":false,\"msg\":\""+Escape.escape("该用户没有赋值角色。")+"\"}", response); return;
		}else{
			redirectStrategy.sendRedirect(request, response, defaultUrl);return ;
		}
		
		List<Map<String,Object>> list = srService.findDistinctSectid(strRoleIdlist.toString());
		StringBuffer strSectIdlist = new StringBuffer();
		for(Iterator<Map<String,Object>> iter = list.iterator();iter.hasNext();){
			Map<String,Object> paramMap = iter.next();
			strSectIdlist.append("'" + paramMap.get("sectid").toString() + "',");
		}
		if(strSectIdlist.length()!=0 && strSectIdlist.lastIndexOf(",")!=-1){
			strSectIdlist.delete(strSectIdlist.lastIndexOf(","), strSectIdlist.length());
		}else if(StringUtils.isNotEmpty(login_mode) && PmcAttributes.PMC_LOGIN_MODE.equalsIgnoreCase(login_mode)){  //登录模式为Ajax
			Httptear.ResponseResultByUTF8("{\"success\":false,\"msg\":\""+Escape.escape("该用户没有任何访问权限。")+"\"}", response); return;
		}else{
			redirectStrategy.sendRedirect(request, response, defaultUrl);return ;
		}
		//构造二级菜单开始
		List<Map<String,Object>> jsonMenu = new ArrayList<Map<String,Object>>();
		List<TSect> sectParentList = srService.findParentSect(groupid,1);
		if(sectParentList != null && sectParentList.size() > 0){
			for(TSect pSect: sectParentList){
				//获取分组下的资源
				List<TSect> sectlist = srService.findSectListByParentidForUser(groupid,pSect.getId(), strSectIdlist.toString());
				if(sectlist!=null && sectlist.size()>0){
					Map<String,Object> pmenu = new HashMap<String,Object>();
					pmenu.put("groupid", pSect.getId());
					pmenu.put("groupname", pSect.getComments());
					pmenu.put("icon", pSect.getIcon());
					List<Map<String,Object>> cmenu = new ArrayList<Map<String,Object>>();
					for(TSect oSect : sectlist){
						Map<String,Object> menuitem = new HashMap<String,Object>();
						menuitem.put("id", oSect.getId()!=null ? oSect.getId().toString().trim() : "");
						menuitem.put("pid", oSect.getPid()!=null ? oSect.getPid().toString().trim() : "");
						menuitem.put("title", oSect.getComments()!=null ? oSect.getComments().toString().trim() : "");
						menuitem.put("url", oSect.getSectname()!=null ? oSect.getSectname().toString().trim() : "");
						menuitem.put("icon", oSect.getIcon()!=null ? oSect.getIcon().toString().trim() : "");
						menuitem.put("remark", oSect.getRemark()!=null? oSect.getRemark().toString().trim(): "");
						menuitem.put("leaf", "true");
						cmenu.add(menuitem);
					}
					pmenu.put("children", cmenu);
					jsonMenu.add(pmenu);
				}
			}
		}
		//把拼接成的频道详情列表信息  存放入session
		WebUtils.setSessionAttribute(request, PmcAttributes.PMC_USER_MENU, JsonUtils.objectToJson(jsonMenu));
		
		System.out.println("[com.pmc.dwa.security.handler.LoginAuthenticationSuccesssHandler]User "+username+" login successful!");
		userService.addSyslog(request, "AuthenticationSuccessHandler", "SuccessAuth", username + "登录成功");
		if(StringUtils.isNotEmpty(login_mode) && PmcAttributes.PMC_LOGIN_MODE.equalsIgnoreCase(login_mode)){  //登录模式为Ajax
			Httptear.ResponseResultByUTF8("{\"success\":true,\"msg\":\""+Escape.escape("用户登录成功。")+"\"}", response);
		}else{
			redirectStrategy.sendRedirect(request, response, defaultUrl);
		}
	}

	/**
	 * @param defaultUrl the defaultUrl to set
	 */
	public void setDefaultUrl(String defaultUrl) {
		this.defaultUrl = defaultUrl;
	}

	/**
	 * @param userService the userService to set
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	/**
	 * @param srService the srService to set
	 */
	public void setSrService(ISectionResourceService srService) {
		this.srService = srService;
	}

	/**
	 * @param modesymbol the modesymbol to set
	 */
	public void setModesymbol(String modesymbol) {
		this.modesymbol = modesymbol;
	}
}
